<% include header.ejs %>
<div id="page-wrapper">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">产品管理</h1>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <div class="row">
        <table id="prodTable" class="table dataTable datatable_ table-striped table-bordered table-condensed">
            <thead>
            <th>id</th>
            <th>产品名</th>
            <th>图片</th>
            <th>销量</th>
            <th>价格</th>
            <th>库存</th>
            <th>上市时间</th>
            <th>描述</th>
            <th>颜色</th>
            <th>规格</th>
            <th>操作</th>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <div class="row">
        <button id="addProd" class="btn btn-info" data-toggle='modal' data-target='#prodAddModel'>新增产品</button>
        <button id="addProdSpec" class="btn btn-info" data-toggle='modal' data-target='#prodSpecAddModel'>新增产品规格</button>
    </div>
</div>
<!-- /#page-wrapper -->

</div>

<div class="modal fade" id="prodUpdateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <!--modal-lg-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">修改产品信息</h4>
            </div>
            <div class="modal-body" style="min-height:350px">
                <form class="form-horizontal" role="form" id="updateprodForm">
                    <div class="form-group">
                        <label for="name" class="col-sm-3 control-label">产品名</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="name"
                                   placeholder="请输入名字">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="price" class="col-sm-3 control-label">价格</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="price"
                                   placeholder="请输入价格">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputfile" class="col-sm-3 control-label">图片重新上传</label>
                        <input autocomplete="off" class="col-sm-9" type="file" id="inputfile">
                        <p id="oinputfile" class="col-sm-9" class="help-block"><a target="_blank" href="">原图片</a></p>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">颜色</label>
                        <div class="acolor colorCheck" class="col-sm-9">
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">规格</label>
                        <div class="aspec specCheck" class="col-sm-9">
                            <label class="col-sm-2"><input name="aspec" type="checkbox" value="1">选项 2</label>
                            <label class="col-sm-2"><input name="aspec"  type="checkbox" value="2">选项 2</label>
                            <label class="col-sm-9"><input name="aspec"  type="checkbox" value="3">选项 2</label>
                            <label class="col-sm-9"><input name="aspec"  type="checkbox" value="4">选项 2</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="qty" class="col-sm-3 control-label">库存</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="qty"
                                   placeholder="请输入库存">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="descr" class="col-sm-3 control-label">描述</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="descr"
                                   placeholder="请输入描述">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="confirmUpdateProd(this)">提交更改</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<div class="modal fade" id="prodSpecAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <!--modal-lg-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">修改产品信息</h4>
            </div>
            <div class="modal-body" style="min-height:350px">
                <!--<p>备注:若新增多条，用空格间隔</p>-->
                <form class="form-horizontal" role="form" id="updateprodForm">
                    <div class="form-group">
                        <label for="color" class="col-sm-3 control-label">颜色</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="color"
                                   placeholder="请输入颜色">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="规格" class="col-sm-3 control-label">规格</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="spec"
                                   placeholder="请输入规格">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="submitSpec" class="btn btn-primary">提交更改</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<div class="modal fade" id="prodAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <!--modal-lg-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">新增产品</h4>
            </div>
            <div class="modal-body" style="min-height:350px">
                <form class="form-horizontal" role="form" id="addprodForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="aname" class="col-sm-3 control-label">产品名</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="aname"
                                   placeholder="请输入名字">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="aprice" class="col-sm-3 control-label">价格</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="aprice"
                                   placeholder="请输入价格">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">颜色</label>
                        <div class="acolor" class="col-sm-9">
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                            <label><input name="acolor" type="checkbox" value="">选项 2</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">规格</label>
                        <div class="aspec" class="col-sm-9">
                            <label class="col-sm-2"><input name="aspec" type="checkbox" value="1">选项 2</label>
                            <label class="col-sm-2"><input name="aspec"  type="checkbox" value="2">选项 2</label>
                            <label class="col-sm-9"><input name="aspec"  type="checkbox" value="3">选项 2</label>
                            <label class="col-sm-9"><input name="aspec"  type="checkbox" value="4">选项 2</label>
                        </div>
                    </div>
                    <!--<div class="form-group">-->
                        <!--<label for="acolor" class="col-sm-3 control-label">颜色</label>-->
                        <!--<div class="col-sm-9">-->
                            <!--<select class="form-control" name="" class="acolor">-->
                                <!--<option value="红色">红色</option>-->
                                <!--<option value="红色">红色</option>-->
                                <!--<option value="红色">红色</option>-->
                            <!--</select>-->
                        <!--</div>-->
                    <!--</div>-->
                    <!--<div class="form-group">-->
                        <!--<label for="aspec" class="col-sm-3 control-label">规格</label>-->
                        <!--<div class="col-sm-9">-->
                            <!--<select class="form-control" name="" class="aspec">-->
                                <!--<option value="红色">红色</option>-->
                                <!--<option value="红色">红色</option>-->
                                <!--<option value="红色">红色</option>-->
                            <!--</select>-->
                        <!--</div>-->
                    <!--</div>-->
                    <div class="form-group">
                        <label for="ainputfile" class="col-sm-3 control-label">图片上传</label>
                        <input autocomplete="off" name="file" class="col-sm-9" type="file" id="ainputfile">
                        <!--<p id="oinputfile" class="col-sm-9" class="help-block"><a target="_blank" href="">原图片</a></p>-->
                    </div>
                    <div class="form-group">
                        <label for="aqty" class="col-sm-3 control-label">库存</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="aqty"
                                   placeholder="请输入库存">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="adescr" class="col-sm-3 control-label">描述</label>
                        <div class="col-sm-9">
                            <input autocomplete="off" type="text" class="form-control" id="adescr"
                                   placeholder="请输入描述">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" data-icon="123" onclick="insertProd(this)">提交更改</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<!--<form id="uploadForm" enctype="multipart/form-data">-->
    <!--<input id="file" type="file" name="file"/>-->
    <!--<button id="upload" type="button">upload</button>-->
<!--</form>-->

<!-- /#wrapper -->
<% include footer.ejs %>
<script type="text/javascript">
    $(function() {
        prod()
        $("#submitSpec").on("click",function(){
            if($("#color").val()!=""&&$("#spec").val()!=""){
                $.ajax({
                    url: 'prod/insertOneSpec',
                    data:{
                        color:$("#color").val(),
                        spec:$("#spec").val()
                    },
                    method: 'post',
                    success: function (res) {
                        if(res.msg =="插入成功"){
                            $(".close").click()
                            alert("插入成功")
                            $("#color").val(""),
                            $("#spec").val("")
                        }
                        else{
                            alert("插入失败")
                        }
                    },
                    error: function () {
                        alert("插入失败")
                    }
                })
            }
            else{
                alert("填写内容不能为空")
            }
        })
        $.ajax({
            url: 'prod/findSpec',
            method: 'post',
            success: function (res) {
//                    console.log(res)
                $(".acolor").html("");
                $(".aspec").html("");
                for(var i = 0;i<res.length;i++){
                    $(".acolor").append("<label><input name='acolor' type='checkbox' " +
                        "value='"+res[i]
                            .color+"'>"+res[i].color+"</label>")
                    $(".aspec").append("<label><input name='aspec' type='checkbox' " +
                        "value='"+res[i]
                            .spec+"'>"+res[i].spec+"</label>")
//                        $("input[name='acolor']").eq(i).val(res[i].color)
                }
            },
            error: function () {
                alert("插入失败")
            }
        })
//        $("#addProd").click(function(){
//            $.ajax({
//                url: 'prod/findSpec',
//                method: 'post',
//                success: function (res) {
////                    console.log(res)
//                    $(".acolor").html("");
//                    $(".aspec").html("");
//                    for(var i = 0;i<res.length;i++){
//                        $(".acolor").append("<label><input name='acolor' type='checkbox' " +
//                            "value='"+res[i]
//                            .color+"'>"+res[i].color+"</label>")
//                        $(".aspec").append("<label><input name='aspec' type='checkbox' " +
//                            "value='"+res[i]
//                            .spec+"'>"+res[i].spec+"</label>")
////                        $("input[name='acolor']").eq(i).val(res[i].color)
//                    }
//                },
//                error: function () {
//                    alert("插入失败")
//                }
//            })
//        })
    })
    function prod(){
        $.ajax({
            url: 'prod/findAllAction',
//            data:'',
            method: 'post',
            success: function (res) {
//                console.log(res)
                prodTable(res)
            },
            error: function () {

            }
        })
    }
    function prodTable(data){
        $('#prodTable').DataTable({
            destroy: true,
            "bAutoWidth": false,
            responsive: true,
            data: data,
            //使用对象数组，一定要配置columns，告诉 DataTables 每列对应的属性
            "aoColumnDefs": [
                { "bSortable": false, "aTargets": [1,2,7,8,9,10] },
                {
                    "render": function(data, type, row) {
                        return ((new Date(parseInt(data))).toLocaleString()=="Invalid Date"?"时间格式错误":(new Date(parseInt(data))).toLocaleString());
                    },
                    "targets": 6
                },
                {
                    "render": function(data, type, row) {
                        var html;
                        html = "<button data-id="+data.id+" class='btn btn-sm btn-primary updateProd' " +
                            "data-toggle='modal' " +
                            "data-target='#prodUpdateModel' onclick='prodUpdateModel(this)'>修改</button>"+
                            "<button data-id="+data.id+" class='btn btn-sm btn-danger' onclick='deleteProd(this)" +
                            "'>删除</button>"
                        return html
                    },
                    "targets": 10
                },
                {
                    "render": function(data, type, row) {
//                        console.log(data)
                        var html;
                        html = "<img src='"+data+"'/>"
                        return html
                    },
                    "targets": 2
                },
            ],
            columns: [
                {
                    data: 'id'
                },{
                    data: 'name'
                },{
                    data: 'icon'
                },{
                    data: 'sales'
                },{
                    data: 'price'
                },{
                    data: 'qty'
                },{
                    data: 'creationTime',
                },{
                    data: 'description'
                }
                ,{
                    data: 'color'
                }
                ,{
                    data: 'spec'
                },
                {
                    data: null
                },
            ],
            language: {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            "fnCreatedRow": function (nRow, aData, iDataIndex) {

            },
            "fnRowCallback": function (nRow, aaData, iDisplayIndex, iDisplayIndexFull) {
            }
        })
    }
    function prodUpdateModel(btn){
//        var id =
        var id = $(btn).attr('data-id');
        $.ajax({
            url: 'prod/findOneById',
            data:{
                id:id
            },
            method: 'post',
            success: function (res) {
                console.log(res)
                var data = res[0]
                $('#name').val(data.name)
                $('#name').attr('data-id',data.id)
                $('#name').attr('data-ct',data.creationTime)
                $('#inputfile').attr('data-icon',data.icon)
                $('#oinputfile').children('a').attr('href',data.icon)
                $('#price').val(data.price)
                $('#qty').val(data.qty)
                $('#descr').val(data.description)

                var color = res[0].color.split(",")
                var spec = res[0].spec.split(",")
                console.log(color.length)
                for(var i=0;i<color.length;i++){
                    for(var j=0;j<$('.colorCheck').children().length;j++){
                        if(color[i] == $('.colorCheck').find("input").eq(j).val()){
                            $('.colorCheck').find("input").eq(j)[0].checked = true
                        }
                    }
                }
                for(var i=0;i<spec.length;i++){
                    for(var j=0;j<$('.specCheck').children().length;j++){
                        if(spec[i] == $('.specCheck').find("input").eq(j).val()){
                            $('.specCheck').find("input").eq(j)[0].checked = true
                        }
                    }
                }
            },
            error: function () {

            }
        })

    }
    function confirmUpdateProd(btn) {
        if(!$("#inputfile").val()){
            var specarr = [];
            var colorarr = []
            var ct = new Date().getTime()
            for (var i = 0; i < $(".specCheck input[name='aspec']:checked").length; i++) {
                specarr.push($(".specCheck input[name='aspec']:checked").eq(i).val())
            }
            for (var i = 0; i < $(".colorCheck input[name='acolor']:checked").length; i++) {
                colorarr.push($(".colorCheck input[name='acolor']:checked").eq(i).val())
            }
            var color = colorarr.join(',');
            var spec = specarr.join(",")
            var d = {
                name: $('#name').val(),
                id: $('#name').attr('data-id'),
                qty: $('#qty').val(),
                description: $('#descr').val(),
                price: $('#price').val(),
                creationTime: ct,
                icon: $("#oinputfile a").attr("href"),
                color: color,
                spec: spec
            }
            console.log(d)
            $.ajax({
                url: 'prod/updateByIdNophoto',
                data:d,
                method: 'post',
                success: function (res) {
//                alert(res.msg)
//                console.log(res.msg)
                    prod()
                    if(res.msg==undefined) {
                        alert("修改成功")
                    }
                },
                error: function () {

                }

            })
        }
        else{
            var inputfile;
            if ($('#inputfile').val() == "") {
                inputfile = $('#inputfile').attr('data-icon')
            }
            else {
                inputfile = $('#inputfile').val()
            }
            var specarr = [];
            var colorarr = []
            for (var i = 0; i < $(".specCheck input[name='aspec']:checked").length; i++) {
                specarr.push($(".specCheck input[name='aspec']:checked").eq(i).val())
            }
            for (var i = 0; i < $(".colorCheck input[name='acolor']:checked").length; i++) {
                colorarr.push($(".colorCheck input[name='acolor']:checked").eq(i).val())
            }
//        console.log(color.join(","))
            var color = colorarr.join(',');
            var spec = specarr.join(",")
            var ct = new Date().getTime()
            var d = [{
                name: $('#name').val(),
                id: $('#name').attr('data-id'),
                qty: $('#qty').val(),
                description: $('#descr').val(),
                price: $('#price').val(),
                creationTime: ct,
                icon: inputfile,
                color: color,
                spec: spec
            }]
            var filename = $("#inputfile").val();
            var data = new FormData();
            var files = $("#inputfile")[0].files;
            var ct = new Date().getTime()
            var a = JSON.stringify(d)
            console.log(a)
            if (files) {
                data.append("file", files[0]);
                data.append("fields", a)
                console.log(data)
                $.ajax({
                    url: 'prod/updateById',
                    type: 'POST',
                    data: data,
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        prod()
                        alert(data.msg)
                        console.log(data)
                    },
                    error: function (err) {
                        console.log(err);
                    }

                })
            }
        }
    }
    function deleteProd(btn){
//        alert("2")
        var id = $(btn).attr('data-id');
        $.ajax({
            url: 'prod/deteleProdById',
            data:{
                id:id
            },
            method: 'post',
            success: function (res) {
//                alert(res.msg)
//                console.log(res.msg)
                prod()
                if(res.msg==undefined) {
                    alert("删除成功")
                }
            },
            error: function () {

            }

        })
    }
    function insertProd(btn){
        var inputfile;
        var specarr = []
        var colorarr = []
        var ct = new Date().getTime()
        for(var i =0;i<$("input[name='aspec']:checked").length;i++){
            specarr.push($("input[name='aspec']:checked").eq(i).val())
        }
        for(var i =0;i<$("input[name='acolor']:checked").length;i++){
            colorarr.push($("input[name='acolor']:checked").eq(i).val())
        }
//        console.log(color.join(","))
        var color = colorarr.join(',');
        var spec = specarr.join(",")
//        console.log(color)
        if($('#ainputfile').val()==""){
            inputfile = "123"
        }
        else {
            var filename = $("#ainputfile").val();
            var data = new FormData();
            var files = $("#ainputfile")[0].files;
            var d = [{
                name: $('#aname').val(),
                qty: $('#aqty').val(),
                description: $('#adescr').val(),
                price: $('#aprice').val(),
                creationTime: ct,
                sales: 0,
                icon: inputfile,
                color: color,
                spec: spec
            }]
            var a = JSON.stringify(d)
            console.log(a)
                if(files){
                    data.append("file", files[0]);
                    data.append("fields",a)
                    console.log(data)
                    $.ajax({
                        url: 'prod/up',
                        type: 'POST',
                        data: data,
                        async: false,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function(data){
                            console.log(data)
                        },
                        error: function(err){
                            console.log(err);
                        }
                    })
                }
//        console.log(data)
//        $.ajax({
//            url: 'prod/insertOne',
//            data:data,
//            method: 'post',
//            success: function (res){
////                alert(res.msg)
//                console.log(res.msg)
//                if(res.msg!=undefined&&res.msg!='fail'){
//                    alert("插入成功")
//                    prod()
//                }
//            },
//            error: function () {
//
//            }
//
//        })
        }
    }

//    function judgePhotoExt(name){
//        if(name.length === 0){
//            $("#upfiletip").css("color","red");
//            $("#upfiletip").text = "你没有选择任何图片！！！"
//            return false;
//        }
//        var extName = name.substring(name.lastIndexOf('.'),name.length).toLowerCase();
//        if(extName != '.png' && extName != '.ipg'){
//            $("#upfiletip").css("color","red");
//            $("#upfiletip").text = "只支持png和ipg格式的格式的文件!!!"
//            return false;
//        }
//        return true;
//    }
</script>
</html>